package com.ry.novel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ry.novel.enums.ResponseStatus;
import com.ry.novel.exception.BusinessException;
import com.ry.novel.model.dto.AuthorInfo;
import com.ry.novel.model.dto.BookInfo;
import com.ry.novel.model.dto.condition.AuthorQuery;
import com.ry.novel.model.resp.Result;
import com.ry.novel.service.AuthorService;
import com.ry.novel.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Response;
import java.util.List;

/**
 * @author ry
 * @since 2022-04-07 07:51
 **/
@RequestMapping("/author")
@RestController
@Slf4j
public class AuthorController {
    @Autowired
    private AuthorService authorService;

    @Autowired
    private BookService bookService;

    @PostMapping("/queryAuthor")
    public Result<Page<AuthorInfo>> queryAuthor(@RequestBody AuthorQuery authorQuery) {
        log.info("authorQuery = " + authorQuery);
        Page<AuthorInfo> infoPage = authorService.queryAuthor(authorQuery);

        return Result.ok(infoPage);
    }

    @PostMapping("/addAuthor")
    public Result<Void> addAuthor(@RequestBody AuthorInfo authorInfo) {
        authorService.addAuthor(authorInfo);

        return Result.ok();
    }

    @PostMapping("/deleteAuthor")
    public Result<Void> deleteAuthor(@RequestParam("id") Long id) {
        List<BookInfo> bookInfos = bookService.queryByAuthorId(id);
        if (bookInfos == null || bookInfos.isEmpty()){
           throw new BusinessException(ResponseStatus.AUTHOR_DELETE_ERROR);
        }

        authorService.deleteAuthor(id);

        return Result.ok();
    }

    @PostMapping("/updateAuthor")
    public Result<Void> updateAuthor(@RequestBody AuthorInfo authorInfo) {
        authorService.updateAuthor(authorInfo);

        return Result.ok();
    }

    @GetMapping("/queryAllAuthor")
    public Result<List<AuthorInfo>> queryAllAuthor() {
        List<AuthorInfo> authorInfos = authorService.queryAll();

        return Result.ok(authorInfos);
    }
}
